package com.neborosoft.lib.collections.algorithms;

import com.neborosoft.lib.collections.Containers;
import com.neborosoft.lib.collections.ListItemGetter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Project: FlyingDog
 * User: stikhonenko
 * Date: 3/11/13
 * Time: 6:26 PM
 */
public class SortedListItemGetter<T> implements ListItemGetter<T>{
    private List<T> list;
    private List<T> sortedList;

    private void initSortedList(){
        if(sortedList == null){
            sortedList = new ArrayList<T>(list);
        }
    }

    public SortedListItemGetter(List<T> list) {
        this.list = list;
        sort();
    }

    public SortedListItemGetter(List<T> list, Comparator<T> comparator) {
        this.list = list;
        sort(comparator);
    }

    public List<T> getList() {
        return list;
    }

    public List<T> getSortedList() {
        return Collections.unmodifiableList(sortedList);
    }

    public void setList(List<T> list) {
        this.list = list;
        sortedList = null;
    }

    public void sort(Comparator<T> comparator){
        initSortedList();
        Collections.sort(sortedList, comparator);
    }

    public void sort(){
        sort(Comparators.<T>defaultComparator());
    }

    public void sort(ListItemComparator<T> comparator){
        initSortedList();
        Containers.sortUsingListItemComparator(sortedList, comparator);
    }

    @Override
    public T getElement(int index) {
        if(sortedList != null){
            return sortedList.get(index);
        } else {
            return list.get(index);
        }
    }
}
